package org.javaymw.springboot.controller;

import org.javaymw.springboot.base.BaseController;
import org.javaymw.springboot.util.MessageUtils;
import org.javaymw.springboot.util.VerifyCodeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/7/12 11:12
 * @Description: 图形验证码
 */
@Controller
@RequestMapping(value = "/captcha")
public class CaptchaController extends BaseController {

    /**
     * 前后端分离 图形验证码 解决方案
     * 1.生成一个唯一码，存放到header里面
     * 2.生成图形验证码，存放到缓存里面
     * 3.后端验证的时候，前端传递唯一码和图形验证码
     * @return
     */
    @RequestMapping(value = "/code")
    public void code(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 设置不缓存验证码图片
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/jpeg");

            // 生成图形验证码唯一码
            UUID pictureId = UUID.randomUUID();
            // 把唯一码放到Header里面，供前端提交图形验证码的时候带过来该参数
            response.setHeader("pictureId", pictureId.toString());

            // 生成图形验证码
            String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
            // 把唯一码(key)，图形验证码(value)放到缓存里面，这里使用session
            request.getSession().setAttribute(sessionProvider.getSessionId(request), verifyCode);

            // 输出流
            int w = 210, h = 45;
            VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 找回密码
     * 1.校验图形验证码是否正确
     * @param checkCode
     * @return
     */
    @RequestMapping(value = "/check", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> signIn(@RequestParam("checkCode") String checkCode, HttpServletRequest request) {
        Map<String, Object> retMap = null;
        try {
            if (!getAttribute(request, getSessionId(request)).equals(checkCode)){
                retMap = MessageUtils.error("请输入正确的图形验证码");
                return retMap;
            }
            retMap = MessageUtils.success();
        } catch (Exception e) {
            retMap = MessageUtils.error();
        }
        return retMap;
    }
}
